﻿using System;
using System.Windows.Forms;
using NanoERP.Infrastructure;
using NanoERP.Business.BaseInfo;
using DevComponents.AdvTree;
using NanoERP.Model;
using System.Collections.Generic;
using NanoERP.Common;
using System.Collections;
using NanoERP.Business.BillInfo;


namespace NanoERP.BaseInfo
{
    //[Module("FrmBillList")]
    public partial class FrmSelectPurchaseOrder : ModuleForm
    {
        readonly SysdictableBLL _sysdictablebLl;
        readonly  OrderinfoBLL _orderinfoBLL;
        readonly ClientinfoBLL _clientBLL;
        const int BillType = 1;
        int _billStatus = -1;
        int _ExecuteStatus = -1;
        long _clientid;
        Clientinfo _clientInfo;
        readonly Dictionary<long, Orderdetail> _dicOrderdetail;
        const string SeletedCell = "SELECTED";
        public string SelectedBillNo="";

        public FrmSelectPurchaseOrder(long clientid, bool isCheckBoxCell = false)
        {
            InitializeComponent();
            _orderinfoBLL = new OrderinfoBLL();
            _sysdictablebLl = new SysdictableBLL();
            _clientBLL = new ClientinfoBLL();
            _dicOrderdetail = new Dictionary<long, Orderdetail>();
            _clientid = clientid;
            _clientInfo = _clientBLL.Get(_clientid);
            if (_clientInfo != null)
                txtClientid.Text = _clientInfo.Clientname;
            BindCombox();
        }

        void BindCombox()
        {
            DictionaryEntry de;
            //绑定订单审批状态
            cmbStatus.Items.Clear();
            cmbStatus.Items.Add(new DictionaryEntry("",0));
            Type statusType = typeof(BillStateEnum);
            int[] arr = (int[])(Enum.GetValues(statusType));     
            string[] names= Enum.GetNames(statusType);
            List<string> _statusList = new List<string>();
            _statusList.Add("待审核");
            _statusList.Add("一级审核");
            //_statusList.Add("红冲");
            //_statusList.Add("作废");
            cmbStatus.Items.Add(new DictionaryEntry("",0));
            for (int i=0;i<names.Length;i++)
            {
                if (!_statusList.Contains(names[i]))
                    continue;
               cmbStatus.Items.Add(new DictionaryEntry(names[i], arr[i]));
               if (arr[i] == (int)(BillStateEnum.一级审核))
                   cmbStatus.SelectedIndex = cmbStatus.Items.Count - 1;
            }
            cmbStatus.DisplayMember = "Key";
            cmbStatus.ValueMember = "Value";

            //绑定订单执行状态
            cmbStatus.Items.Clear();
            cmbStatus.Items.Add(new DictionaryEntry("", 0));
            statusType = typeof(BillExuStateEnum);
            arr = (int[])(Enum.GetValues(statusType));
            names = Enum.GetNames(statusType);
            _statusList = new List<string>();
            _statusList.Add("未完成");
            _statusList.Add("已完成");
            //_statusList.Add("红冲");
            //_statusList.Add("作废");
            cmbExecuteStatus.Items.Add(new DictionaryEntry("", 0));
            for (int i = 0; i < names.Length; i++)
            {
                if (!_statusList.Contains(names[i]))
                    continue;
                cmbExecuteStatus.Items.Add(new DictionaryEntry(names[i], arr[i]));
                if (arr[i] == (int)(BillExuStateEnum.未完成))
                    cmbExecuteStatus.SelectedIndex = cmbExecuteStatus.Items.Count - 1;
            }
            cmbExecuteStatus.DisplayMember = "Key";
            cmbExecuteStatus.ValueMember = "Value";
          
        }

        /// <summary>
        /// 
        /// </summary>
        void QueryInfo()
        {
            DateTime dtFrom = DateTime.MinValue;
            DateTime dtTo = DateTime.MaxValue;
            if (checkDate.Checked)
            {
                dtFrom = dtp_from.Value;
                dtTo = dtp_to.Value;
            }
            dgvOrderList.AutoGenerateColumns = false;
            dgvOrderList.DataSource = _orderinfoBLL.Query(BillType, _clientid, 0, "", 0, 0, 0, txtOrderNo.Text, "", dtFrom, dtTo, _billStatus, _ExecuteStatus);
        }
        /// <summary>
        /// 绑定采购订单商品明细
        /// </summary>
        void BindDetailContro(int index)
        {
            //SetToolButtonEnableld((BillStateEnum)_orderinfo.State.Value);
            UnitColumn.DisplayMember = "DICNAME";
            UnitColumn.ValueMember = "DICNAME";
            UnitColumn.DataSource = _sysdictablebLl.Query((int)SysDicEnum.基本单位);

            List<Orderinfo> orderList = (List<Orderinfo>)dgvOrderList.DataSource;
            if (orderList.Count <= index)
             
            {
                dgvDetailList.DataSource = null;
                return;
            }
            _dicOrderdetail.Clear();
            Orderinfo o = orderList[index];
            SelectedBillNo = o.Orderno;
            if (o.ListOrderdetail == null) return;
            dgvDetailList.DataSource = null;
            dgvDetailList.AutoGenerateColumns = false;
            dgvDetailList.DataSource = o.ListOrderdetail;
            DetailSelect(true);
        }
        /// <summary>
        /// 全选、取消反选
        /// </summary>
        /// <param name="selected">是否选中</param>
        private void DetailSelect(bool selected)
        {
             for (int i = 0; i < dgvDetailList.Rows.Count; i++)
            {
                 dgvDetailList.Rows[i].Cells[SeletedCell].Value = selected?1:0;
                 CellChange(dgvDetailList,new DataGridViewCellEventArgs(1,i));
            }
        }

        /// <summary>
        /// 递归循环调用
        /// </summary>
        /// <param name="firList">一级树集合</param>
        /// <param name="parentNode">上级节点</param>
        void RecursiveLoopNodes(List<Sysdictable> firList, Node parentNode)
        {
            firList.ForEach(r =>
            {
                var secNode = new Node(r.Dicname) { Tag = r, Name = r.Id.ToString(), Image = NanoERP.Properties.Resources.CreateTableTemplatesGallery };

                parentNode.Nodes.Add(secNode);
                var recList = _sysdictablebLl.Query(r.Id);
                if (recList.Count > 0)
                    RecursiveLoopNodes(recList, secNode);
            });
        }

        private void tsbSelectType_Click(object sender, EventArgs e)
        {
            if (_dicOrderdetail.Count < 1)
            {
                MessageBox.Show(@"没有选择订单明细，请重新检索后选择记录！", @"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            this.Tag = _dicOrderdetail;
            this.DialogResult = DialogResult.OK;
        }
        private void tsbAdd_Click(object sender, EventArgs e)
        {
            panelEx2.Height = panelEx3.Top - panelEx2.Top - 35;
            panelEx2.BringToFront();
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            panelEx2.Height = this.Height - panelEx2.Top - 30;
            panelEx2.BringToFront();
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            //if (dgvList.CurrentRow == null) return;
            //var obj = dgvList.CurrentRow.DataBoundItem as Storageinfo;
            //var text = string.Format(@"您要确定要“删除”当前仓库“{0}”吗？", obj.Stoname);
            //if (MessageBox.Show(text, "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            //{
            //    _storageinfoBLL.Delete(obj.Id);
            //    QueryInfo();
            //}
        }

        private void tsbPrint_Click(object sender, EventArgs e)
        {

        }

        private void tsbExport_Click(object sender, EventArgs e)
        {
            string msgLog;
            ExcelUtil.ExportToExcel(dgvList, "分支机构信息", out msgLog);
            if (msgLog != null)
                MessageBox.Show(msgLog, @"提示消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            QueryInfo();
            BindDetailContro(0);
        }

        private void dicTree_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            QueryInfo();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            tsbEdit_Click(null, null);
        }

        private void dgvList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            ControlUtil.DataGridRowPostPaint(sender, e);
        }

        private void FrmStorageinfoList_Load(object sender, EventArgs e)
        {

        }

        private void cmbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbStatus.SelectedIndex < 0)
                _billStatus = -1;
            else
            {
                _billStatus = Normal.ToInt(((DictionaryEntry)(cmbStatus.Items[cmbStatus.SelectedIndex])).Value);
            }
        }


        private void dgvOrderList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvOrderList.SelectedRows.Count != 1)
                return;
            BindDetailContro(dgvOrderList.SelectedRows[0].Index);
        }
        private void CellChange(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            if (dgvDetailList.Columns[e.ColumnIndex].Name == SeletedCell)
            {
                try
                {
                    var currRow = dgvDetailList.Rows[e.RowIndex];
                    var checkCell = (DataGridViewCheckBoxCell)currRow.Cells[SeletedCell];
                    var vv = currRow.DataBoundItem as Orderdetail;

                    if (checkCell.Value.ToString().Equals("1"))
                        _dicOrderdetail.Add(vv.Id, vv);
                    else
                        _dicOrderdetail.Remove(vv.Id);
                }
                catch { }
                dgvDetailList.Invalidate();
            }
        }
     
        private void dgvDetailList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
              if (e.RowIndex == -1) return;
              if (dgvDetailList.Columns[e.ColumnIndex].Name == SeletedCell)
              {
                  var currRow = dgvDetailList.Rows[e.RowIndex];
                  var checkCell = (DataGridViewCheckBoxCell)currRow.Cells[SeletedCell];
                  checkCell.Value = (checkCell.Value.ToString()=="0") ? 1 : 0;
              }
              CellChange(sender, e);
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            DetailSelect(true);
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            DetailSelect(false);
        }

        private void cmbExecuteStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbExecuteStatus.SelectedIndex < 0)
                _ExecuteStatus = -1;
            else
            {
                _ExecuteStatus = Normal.ToInt(((DictionaryEntry)(cmbExecuteStatus.Items[cmbExecuteStatus.SelectedIndex])).Value);
            }
        }
    }
}
